//
//  WYNetworking.m
//  WuyouTang
//
//  Created by YunBao on 2018/6/6.
//  Copyright © 2018年 cat. All rights reserved.
//

#import "WYNetworking.h"
#import "iOSNetworking.h"

@interface WYNetworking()



@end

static AFHTTPSessionManager *_netManager = nil;

@implementation WYNetworking

+(AFHTTPSessionManager *)ybnetManager{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _netManager = [AFHTTPSessionManager manager];
        
    });
    return _netManager;
}

//+(void)getQCloudWithUrl:(NSString *)url Suc:(PullSuccessBlock)sucBack Fail:(PullFailBlock)failBack {
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    [session GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSString *code = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]];
//        NSDictionary *data = [responseObject valueForKey:@"data"];
//        NSString *msg = [NSString stringWithFormat:@"%@-%@",[responseObject objectForKey:@"message"],[responseObject objectForKey:@"codeDesc"]];
//        //回调
//        sucBack(data,code,msg);
//
//    }failure:^(NSURLSessionDataTask *task, NSError *error)     {
//        [MBProgressHUD showPop:@"网络错误"];
//        //必须判断failback是否存在
//        if (failBack) {
//            failBack(error);
//        }
//    }];
//}
+(void)getQCloudWithUrl:(NSString *)url Suc:(PullSuccessBlock)sucBack Fail:(PullFailBlock)failBack {
    //AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [[WYNetworking ybnetManager] GET:url parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        int code = [[NSString stringWithFormat:@"%@",[responseObject objectForKey:@"code"]] intValue];
        NSDictionary *data = [responseObject valueForKey:@"data"];
        NSString *msg = [NSString stringWithFormat:@"%@-%@",[responseObject objectForKey:@"message"],[responseObject objectForKey:@"codeDesc"]];
        //回调
        sucBack(code,data,msg);
        
    }failure:^(NSURLSessionDataTask *task, NSError *error)     {
        [MBProgressHUD showPop:YZMsg(@"网络错误")];
        //必须判断failback是否存在
        if (failBack) {
            failBack(error);
        }
    }];
}
//+(void)postWithUrl:(NSString *)url Dic:(NSDictionary *)dic Suc:(PullSuccessBlock)sucBack Fail:(PullFailBlock)failBack {
//    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
//    //NSString *pullUrl = [purl stringByAppendingFormat:@"?service=%@",url];//index.php
//    [session POST:url parameters:dic progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSNumber *number = [responseObject valueForKey:@"ret"] ;
//        if([number isEqualToNumber:[NSNumber numberWithInt:200]]) {
//            NSDictionary *data = [responseObject valueForKey:@"data"];
//            NSString *code = [NSString stringWithFormat:@"%@",[data valueForKey:@"code"]];
//            NSString *msg = [NSString stringWithFormat:@"%@",[data valueForKey:@"msg"]];
//            //回调
//            sucBack(data,code,msg);
//        }else{
//            NSString *erro_fun = [self getFunName:url];
//            sucBack(@{},@"9999",[NSString stringWithFormat:@"接口错误:%@-%@\n%@",number,erro_fun,[responseObject valueForKey:@"msg"]]);
//        }
//    }failure:^(NSURLSessionDataTask *task, NSError *error)     {
//        [MBProgressHUD showPop:@"网络错误"];
//        //必须判断failback是否存在
//        if (failBack) {
//            failBack(error);
//        }
//    }];
//}

#pragma mark - AF
//+(void)postWithUrl:(NSString *)url Dic:(NSDictionary *)dic Suc:(PullSuccessBlock)sucBack Fail:(PullFailBlock)failBack {
//
//    NSString *pullUrl = [purl stringByAppendingFormat:@"?service=%@",url];//index.php
//    pullUrl = [pullUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
//
//    NSMutableDictionary *pullDic = [[NSMutableDictionary alloc]initWithDictionarytionary:dic];
//    if (![PublicObj checkNull:[Config getOwnID]]) {
//        [pullDic addEntriesFromDictionary:@{@"uid":[Config getOwnID],@"token":[Config getOwnToken]}];
//    }
//    [pullDic addEntriesFromDictionary:@{@"version_ios":[PublicObj getAppBuild],@"mobileid":[PublicObj getDeviceUUID],@"device":[PublicObj iphoneType]}];
//    //NSLog(@"请求参数(%@)：%@\n\nfullUrl:\n%@%@\n",pullUrl,pullDic,pullUrl,[self getStrWithDic:pullDic]);
//    NSLog(@"\nfullUrl:\n%@%@\n",pullUrl,[self getStrWithDic:pullDic]);
//    [[WYNetworking ybnetManager] POST:pullUrl parameters:pullDic headers:nil progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
//        NSNumber *number = [responseObject valueForKey:@"ret"] ;
//        if([number isEqualToNumber:[NSNumber numberWithInt:200]]) {
//            //NSLog(@"获取参数(%@):%@",pullUrl,responseObject);
//            NSDictionary *data = [responseObject valueForKey:@"data"];
//            id info = [data valueForKey:@"info"];
//            int code = [minstr([data valueForKey:@"code"]) intValue];
//            NSString *msg = [NSString stringWithFormat:@"%@",[data valueForKey:@"msg"]];
//            //回调
//            sucBack(code,info,msg);
//            if (code == 700) {
//                dispatch_async(dispatch_get_main_queue(), ^{
//                    [MBProgressHUD hideHUD];
//                    [PublicObj tokenExpired:msg];
//                });
//                NSLog(@"====%@",pullUrl);
//            }
//        }else{
//            //NSString *erro_fun = [self getFunName:pullUrl];
//            sucBack(999,@[],[NSString stringWithFormat:@"%@:%@-%@\n%@",YZMsg(@"接口错误"),number,url,[responseObject valueForKey:@"msg"]]);
//        }
//    }failure:^(NSURLSessionDataTask *task, NSError *error)     {
//        //必须判断failback是否存在
//        if (failBack) {
//            failBack(error);
//        }
//        [MBProgressHUD showPop:YZMsg(@"网络错误")];
//        /*
//        NSString *msg = [NSString stringWithFormat:@"%@-\n%@",error,pullDic];
//        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"error" message:msg preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancelA = [UIAlertAction actionWithTitle:@"复制" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//            UIPasteboard *paste = [UIPasteboard generalPasteboard];
//            paste.string = msg;
//        }];
//        UIViewController *currentVC = [UIApplication sharedApplication].delegate.window.rootViewController;
//        [alertC addAction:cancelA];
//        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//            [currentVC presentViewController:alertC animated:YES completion:nil];
//        });
//        */
//
//    }];
//}
#pragma mark -

+(void)postWithUrl:(NSString *)url Dic:(NSDictionary *)dic Suc:(PullSuccessBlock)sucBack Fail:(PullFailBlock)failBack {
    [iOSNetworking postWithURL:url params:dic success:^(NSURLResponse *response, id responseObject) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSNumber *number = [responseObject valueForKey:@"ret"] ;
            if([number isEqualToNumber:[NSNumber numberWithInt:200]]) {
                
                NSDictionary *data = [responseObject valueForKey:@"data"];
                id info = [data valueForKey:@"info"];
                int code = [minstr([data valueForKey:@"code"]) intValue];
                NSString *msg = [NSString stringWithFormat:@"%@",[data valueForKey:@"msg"]];
                //回调
                if (sucBack) {
                    sucBack(code,info,msg);
                }
                if (code == 700) {
                    [MBProgressHUD hideHUD];
                    [PublicObj tokenExpired:msg];
                    NSLog(@"====%@",url);
                }
            }else{
                if (sucBack) {
                    NSString *resDes = [PublicObj checkNull:minstr([responseObject valueForKey:@"msg"])]?@"":minstr([responseObject valueForKey:@"msg"]);
                    NSString *failDesStr = [NSString stringWithFormat:@"%@:%@\n%@-%@",YZMsg(@"接口错误"),minstr([responseObject valueForKey:@"ret"]),url,resDes];
                    NSHTTPURLResponse *httpRes = (NSHTTPURLResponse*)response;
                    if (httpRes.statusCode != 200) {
                        failDesStr = [NSString stringWithFormat:@"%@:%ld\n%@-%@",YZMsg(@"接口错误"),(long)httpRes.statusCode,url,resDes];
                    }
                    sucBack(999,@[],failDesStr);
                }
            }
        });
    } failure:^(NSString *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (failBack) {
                failBack(error);
            }
            [MBProgressHUD showError:YZMsg(@"信息错误")];
        });
    }];
}

+(NSString *)getStrWithDic:(NSDictionary*)dic {
    if ([dic allKeys].count<=0) {
        return @"";
    }
    NSString *urlStr = @"";
    for (NSString *key in [dic allKeys]) {
        NSString *value = minstr([dic valueForKey:key]);
        value = [value stringByReplacingOccurrencesOfString:@" " withString:@""];
        urlStr = [urlStr stringByAppendingFormat:@"&%@=%@",key,value];
    }
    return urlStr;
}

/**
 * 获得接口名称
 * @param url 全地址(eg:xxx/api/public/?service=Video.getRecommendVideos&uid=12470&type=0&p=1)
 * @return 返回的接口名(eg:Video.getRecommendVideos)
 */
+(NSString *)getFunName:(NSString *)url{
    if (![url containsString:@"&"]) {
        url = [url stringByAppendingFormat:@"&"];
    }
    NSRange startRange = [url rangeOfString:@"="];
    NSRange endRange = [url rangeOfString:@"&"];
    NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
    NSString *result = [url substringWithRange:range];
    return result;
}

#pragma mark - 获取视频分类
+(void)getVideoClass:(BOOL)postNot {
    
    [self postWithUrl:@"Video.getClassLists" Dic:@{} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            if ([info isKindOfClass:[NSArray class]]) {
                [common saveVideoClass:info];
                //rk_net
                if (postNot) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"FirstGetVideoClass" object:nil];
                }
            }
        }
    } Fail:^(id fail) {
        
    }];
    
    
}

/// 获取用户关系
+(void)getRelationWithTouid:(NSString *)touid finish:(PullFinishiBlock)finish {
    [WYNetworking postWithUrl:@"User.getUserHome" Dic:@{@"touid":touid} Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            NSDictionary *infoDic = [info firstObject];
            if (finish) {
                finish(0,infoDic);
            }
        }else{
            if (finish) {
                finish(code,@{});
            }
        }
    } Fail:^(id fail) {
        if (finish) {
            finish(-1,@{});
        }
    }];
}

@end
